<script setup>
import { ref, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showWarning } from '../utils/message'

const route = useRoute()
const router = useRouter()

const tags = ref([])

// 添加标签
const addTag = (tag) => {
  const isExist = tags.value.some(item => item.path === tag.path)
  if (!isExist && tag.title) {
    tags.value.push(tag)
  }
}

// 关闭标签
const closeTag = (tag) => {
  if (tag.path === '/') {
    showWarning('首页标签不能关闭')
    return
  }
  
  const index = tags.value.findIndex(item => item.path === tag.path)
  if (index === -1) return
  
  tags.value.splice(index, 1)
  
  // 如果关闭的是当前页面，则跳转到前一个标签
  if (tag.path === route.path) {
    const prevTag = tags.value[Math.max(0, index - 1)]
    router.push(prevTag.path)
  }
}

// 初始化时添加首页标签
onMounted(() => {
  addTag({
    path: '/',
    title: '首页概览',
    name: 'Home'
  })
  // 如果当前路由不是首页，也添加当前路由的标签
  if (route.path !== '/') {
    addTag({
      path: route.path,
      title: route.meta.title,
      name: route.name
    })
  }
})

// 监听路由变化
watch(
  () => route.path,
  (newPath) => {
    addTag({
      path: newPath,
      title: route.meta.title,
      name: route.name
    })
  },
  { immediate: true }
)
</script>

<template>
  <div class="tags-view-container">
    <el-scrollbar class="tags-view-wrapper">
      <div class="tags-view-item">
        <el-tag
          v-for="tag in tags"
          :key="tag.path"
          :type="route.path === tag.path ? 'primary' : 'info'"
          :closable="tag.path !== '/'"
          class="mx-1"
          :effect="route.path === tag.path ? 'light' : 'plain'"
          @close="closeTag(tag)"
          @click="router.push(tag.path)"
        >
          {{ tag.title }}
        </el-tag>
      </div>
    </el-scrollbar>
  </div>
</template>

<style scoped>
.tags-view-container {
  height: 34px;
  width: 100%;
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-light);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.tags-view-wrapper {
  height: 100%;
}

.tags-view-item {
  padding: 4px 8px;
  display: flex;
  align-items: center;
  gap: 4px;
  height: 100%;
}

.el-tag {
  cursor: pointer;
  margin-right: 4px;
  height: 26px;
  line-height: 26px;
  border-radius: 3px;
  user-select: none;
  padding: 0 8px;
  font-size: 12px;
  
  &:first-of-type {
    margin-left: 15px;
  }

  &:hover {
    transform: translateY(-1px);
  }
}

:deep(.el-scrollbar__wrap) {
  height: 100%;
}
</style>
